package com.yuyang.wifi.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.mine.ForceSpeedGifActivity;
import com.yuyang.wifi.activitys.web.WebViewSecretActivity;
import com.yuyang.wifi.adapter.WifiListAdapter;
import com.yuyang.wifi.base.BaseFragment;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.dialog.AddMainScreenDialog;
import com.yuyang.wifi.dialog.BaseDialogFragment;
import com.yuyang.wifi.dialog.CheckSafeQuestionDialog;
import com.yuyang.wifi.dialog.NetworkContractFailureDialog;
import com.yuyang.wifi.dialog.NetworkSpeedDialog;
import com.yuyang.wifi.dialog.UserProtocolDialog;
import com.yuyang.wifi.dialog.WifiWarnDialog;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.Skip;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.views.recyclerview.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

/**
 * 连接
 */

public class OldContractTabFragment extends BaseFragment {

    @BindView(R.id.tv_network_speed_num)
    TextView tvNetworkSpeedNum;
    @BindView(R.id.tv_network_balance_num)
    TextView tvNetworkBalanceNum;
    @BindView(R.id.tv_network_good_num)
    TextView tvNetworkGoodNum;
    @BindView(R.id.recyclerView_wifi)
    RecyclerView recyclerViewWifi;
    @BindView(R.id.express_container)
    FrameLayout expressContainer;
    @BindView(R.id.express_2_ad_container)
    FrameLayout express2AdContainer;
    @BindView(R.id.tv_contract_wifi_name)
    TextView tvContractWifiName;
    @BindView(R.id.ll_close_wifi_state)
    LinearLayout llCloseWifiState;
    @BindView(R.id.rl_wifi_layout)
    RelativeLayout rlWifiLayout;
    @BindView(R.id.tv_contract_wifi_state)
    TextView tvContractWifiState;

    private WifiListAdapter wifiListAdapter;
    private List<ScanResult> scanResults;
    private List<ScanResult> scanResults1 = new ArrayList<>();
    WifiManager wifiManager;

    public static OldContractTabFragment newInstance() {
        OldContractTabFragment fragment = new OldContractTabFragment();
        return fragment;
    }

    @Override
    protected void initActionBar() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home_tab_page;
    }

    @Override
    protected void initBizView() {
        String agreeProtocol = SpUtil.find(AppConstant.KEY_AGREE_PROTOCOL);
        if (TextUtils.isEmpty(agreeProtocol)) {
            showUserProtocolDialog();
        } else {
            showCheckSafeDialog();
        }
        wifiListAdapter = new WifiListAdapter(getActivity(), scanResults);
        recyclerViewWifi.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));
        recyclerViewWifi.setNestedScrollingEnabled(false);
        recyclerViewWifi.setAdapter(wifiListAdapter);
        wifiListAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }
        });

    }


    private void showUserProtocolDialog() {
        UserProtocolDialog userProtocolDialog = UserProtocolDialog.newInstance();
        userProtocolDialog.setData(getActivity());
        userProtocolDialog.showDialog(getActivity().getFragmentManager());
        userProtocolDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //同意
                userProtocolDialog.dismiss();
                SpUtil.saveOrUpdate(AppConstant.KEY_AGREE_PROTOCOL, "123");
            }

            @Override
            public void onInputConfirm(String... values) {
                //隐私协议
                Intent intent2 = new Intent(getActivity(), WebViewSecretActivity.class);
                intent2.putExtra("url", "file:///android_asset/index.html");
                intent2.putExtra("title", "隐私协议");
                startActivity(intent2);
            }

            @Override
            public void onCancel() {
                //不同意
                ToastUtils.showShortToast(getActivity(), "请您阅读并同意该协议，否则无法使用");
            }

            @Override
            public void onSendCode() {
                Intent intent = new Intent(getActivity(), WebViewSecretActivity.class);
                intent.putExtra("url", "file:///android_asset/index2.html");
                intent.putExtra("title", "注册协议");
                startActivity(intent);
            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (wifiManager.isWifiEnabled() && wifiManager.getConnectionInfo() != null) {
            wifiOpenState();
        } else {
            wifiCloseState();
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        getActivity().registerReceiver(mWifiScanReceiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != mWifiScanReceiver) {
            Log.e("broadReceive====", "onPause: ===unregisterReceiver");
            getActivity().unregisterReceiver(mWifiScanReceiver);
        }
    }


    private void wifiCloseState() {
        llCloseWifiState.setVisibility(View.VISIBLE);
        rlWifiLayout.setVisibility(View.GONE);
        tvContractWifiState.setText("未打开");
    }

    private void wifiOpenState() {
        llCloseWifiState.setVisibility(View.GONE);
        rlWifiLayout.setVisibility(View.VISIBLE);
        tvContractWifiState.setText("已连接");
    }

    private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                try {
                    scanResults = new ArrayList<>();
                    scanResults = wifiManager.getScanResults();
                    if (wifiManager.getConnectionInfo() != null && wifiManager.getConnectionInfo().getIpAddress() != 0) {
                        wifiListAdapter.setConnectionWifi(wifiManager.getConnectionInfo().getSSID().replace("\"", ""));
                    }
                    if (scanResults != null && scanResults.size() > 0) {
                        HashSet h = new HashSet(scanResults);
                        scanResults.clear();
                        scanResults.addAll(h);
                        for (int i = scanResults.size() - 1; i > 0; i--) {
                            if (scanResults.get(i).SSID == null || scanResults.get(i).SSID.isEmpty()) {
                                scanResults.remove(i);
                            } else {
                                if (scanResults.size() > 1) {
                                    if (scanResults.get(i).SSID.equals(wifiManager.getConnectionInfo().getSSID().replace("\"", ""))) {
                                        Collections.swap(scanResults, 0, i);
                                    }
                                }
                            }
                        }
                        scanResults1.clear();
                        wifiListAdapter.removeAll();
                        scanResults1.addAll(scanResults);
                        wifiListAdapter.setNewData(scanResults1);
                        //wifiListAdapter.notifyDataSetChanged();
                    } else {
                        wifiManager.startScan();
                    }
                } catch (Exception e) {

                }
            } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                //wifi开关变化
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    case WifiManager.WIFI_STATE_DISABLED: {
                        //wifi关闭
                        wifiCloseState();
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        //wifi正在关闭
                        Log.e("=====", "正在关闭");
                        Toast.makeText(getActivity(), "wifi正在关闭", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        //wifi已经打开
                        Log.e("=====", "已经打开");
                        wifiOpenState();
                        requestLocationPermission();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        //wifi正在打开
                        Log.e("=====", "正在打开");
                        wifiManager.startScan();
                        Toast.makeText(getActivity(), "wifi正在打开,请稍等", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        //未知
                        Log.e("=====", "未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                //监听wifi连接状态
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.e("=====", "--NetworkInfo--" + info.toString());
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
//                    Log.e("=====", "wifi没连接上");
                    tvContractWifiName.setText("未连接");
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                    if (wifiManager.getConnectionInfo() != null && wifiManager.getConnectionInfo().getIpAddress() != 0) {
                        tvContractWifiName.setText(wifiManager.getConnectionInfo().getSSID().replace("\"", ""));
                        wifiListAdapter.setConnectionWifi(wifiManager.getConnectionInfo().getSSID().replace("\"", ""));
                        wifiOpenState();
                    }
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
//                    Log.e("=====", "wifi正在连接");
                }
            }
        }
    };


    private void requestLocationPermission() {
        //, Manifest.permission.ACCESS_COARSE_LOCATION
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_GAODE_LOCATION, new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (!isLocationEnabled()) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 101);
                            Toast.makeText(getActivity(), "为保证更好的用户体验，请打开定位服务", Toast.LENGTH_SHORT).show();
                        } else {
                            if (wifiManager.isWifiEnabled()) {
                                wifiManager.startScan();
                            }
                        }
                    }

                    @Override
                    public void onPermissionDenied() {

                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }




    public void showCheckSafeDialog() {
        CheckSafeQuestionDialog checkSafeQuestionDialog = CheckSafeQuestionDialog.newInstance();
        checkSafeQuestionDialog.showDialog(getActivity().getFragmentManager());
        checkSafeQuestionDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                Skip.toActivity(getActivity(), ForceSpeedGifActivity.class);
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {

            }
        });
    }

    public void wifiWarnDialog() {
        WifiWarnDialog wifiWarnDialog = WifiWarnDialog.newInstance();
        wifiWarnDialog.showDialog(getActivity().getFragmentManager());
        wifiWarnDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //免费解锁
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {
                //直接进入
            }
        });
    }

    public void networkSpeedDialog() {
        NetworkSpeedDialog networkSpeedDialog = NetworkSpeedDialog.newInstance();
        networkSpeedDialog.showDialog(getActivity().getFragmentManager());
        networkSpeedDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //立即加速
            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {
                //直接进入
            }
        });
    }


    public void networkContractFailureDialog() {
        NetworkContractFailureDialog networkContractFailureDialog = NetworkContractFailureDialog.newInstance();
        networkContractFailureDialog.showDialog(getActivity().getFragmentManager());
        networkContractFailureDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {

            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {

            }
        });
    }

    public void addMainScreenDialog() {
        AddMainScreenDialog addMainScreenDialog = AddMainScreenDialog.newInstance();
        addMainScreenDialog.showDialog(getActivity().getFragmentManager());
        addMainScreenDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {

            }

            @Override
            public void onInputConfirm(String... values) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSendCode() {

            }
        });
    }


}
